<template>
  <div class="chart">
    <!-- ✅ 为容器添加明确的尺寸 -->
    <div
      ref="chartRef"
      class="monitorContainer"
      :class="chartOption.xAxisData.length > 0 ? 'show' : 'hidden'"
    />
    <empty-data-chart :is-empty="chartOption.xAxisData.length === 0" />
  </div>
</template>

<script setup>
import * as echarts from 'echarts';
import { onMounted, onUnmounted, nextTick, watch, ref, computed } from 'vue';
import EmptyDataChart from '@/components/empty-data-chart/index.vue';

// 定义 props
const props = defineProps({
  chartOption: {
    type: Object,
    default: () => ({
      xAxisData: [],
      yAxisName: '销售额',
      seriesData: []
    })
  }
});

// DOM 引用
const chartRef = ref(null);
let myChart = null;

// 颜色配置
const axisStyleColor1 = ref('#D9D9D9');
const axisStyleColor2 = ref('#999999');
const lineStyleColor = ref('#FF5757');

// 渐变颜色（不是 ref，不要加 .value）
const areaStyleColor = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
  { offset: 0, color: 'rgba(255, 87, 87, 0.5)' },
  { offset: 0.3, color: 'rgba(255, 169, 169, 0.3)' },
  { offset: 1, color: 'rgba(255, 169, 169, 0)' }
]);

// ✅ 计算属性：验证数据长度是否匹配
const isValidData = computed(() => {
  const { xAxisData, seriesData } = props.chartOption;
  return Array.isArray(xAxisData) && 
         Array.isArray(seriesData) && 
         xAxisData.length === seriesData.length && 
         xAxisData.length > 0;
});

// 构建 series
const getSeriesOption = () => {
  if (!isValidData.value) {
    console.warn('Invalid data for line chart:', props.chartOption);
    return [];
  }

  return [
    {
      name: '销售额', // ✅ 添加系列名称（用于图例）
      type: 'line',
      data: props.chartOption.seriesData,
      smooth: true,
      lineStyle: {
        color: lineStyleColor.value,
        width: 3,
        shadowColor: 'rgba(222, 115, 127, 0.23)',
        shadowBlur: 10,
        shadowOffsetY: 8
      },
      areaStyle: {
        color: areaStyleColor
      }
    }
  ];
};

// ✅ 初始化并设置图表（改进时机）
const setOption = async () => {
  // ✅ 确保 DOM 已渲染且有尺寸
  await nextTick();
  
  if (!chartRef.value) {
    console.warn('Chart container ref is not available');
    return;
  }

  // ✅ 检查 DOM 尺寸
  const { offsetWidth, offsetHeight } = chartRef.value;
  if (offsetWidth <= 0 || offsetHeight <= 0) {
    console.warn('Chart container has no width or height:', { width: offsetWidth, height: offsetHeight });
    // 可以稍后重试或等待尺寸变化
    return;
  }

  // 如果已有实例，先 dispose
  if (myChart) {
    myChart.dispose();
  }

  myChart = echarts.init(chartRef.value);

  const option = {
    title: {
      text: '销售额趋势图',
      left: 'center',
      top: '10',
      textStyle: {
        color: '#333333',
        fontWeight: 'bolder',
        fontSize: 14
      }
    },
    grid: {
      left: 30,
      right: 33,
      top: 60,
      bottom: 5,
      containLabel: true
    },
    // ✅ 添加图例
    legend: {
      show: false,
      data: ['销售额']
    },
    xAxis: {
      type: 'category',
      data: props.chartOption.xAxisData,
      axisLine: { lineStyle: { color: axisStyleColor1.value } },
      axisTick: { show: true, lineStyle: { color: axisStyleColor1.value } },
      axisLabel: { align: 'center', color: axisStyleColor2.value },
      // ✅ 确保 boundaryGap 为 false（折线图通常需要）
      boundaryGap: false
    },
    yAxis: {
      type: 'value',
      name: props.chartOption.yAxisName,
      nameTextStyle: { color: axisStyleColor2.value },
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: { color: axisStyleColor2.value },
      splitLine: { lineStyle: { color: axisStyleColor1.value } }
    },
    series: getSeriesOption(),
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        lineStyle: {
          color: axisStyleColor1.value,
          width: 2
        }
      },
      formatter: '销售额：{c}<br />{b}',
      backgroundColor: '#FFFFFF',
      borderColor: '#eef3f8',
      borderWidth: 1,
      textStyle: { color: '#8C8C8C' },
      padding: 12
    }
  };

  myChart.setOption(option);

  // 自适应窗口大小
  window.addEventListener('resize', handleResize);
};

// 窗口 resize 处理
const handleResize = () => {
  myChart?.resize();
};

// 组件挂载后初始化
onMounted(() => {
  // ✅ 使用 setTimeout 确保 DOM 完全渲染后再初始化
  setTimeout(() => {
    setOption();
  }, 0);
});

// 监听 chartOption 变化，自动更新图表
watch(
  () => props.chartOption,
  (newVal, oldVal) => {
    if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
      if (myChart) {
        setOption();
      }
    }
  },
  { deep: true }
);

// 组件卸载前销毁实例
onUnmounted(() => {
  if (myChart) {
    window.removeEventListener('resize', handleResize);
    myChart.dispose();
    myChart = null;
  }
});
</script>

<style lang="scss" scoped>
.chart {
  position: relative;
  display: inline-block;
  width: 50%;
  height: 100%;

  .monitorContainer {
    width: 100%;
    height: 300px;

    &.show {
      visibility: visible;
    }

    &.hidden {
      visibility: hidden;
    }

    & > div,
    & > canvas {
      width: 100% !important;
      height: 100% !important;
    }
  }
}
</style>
